package com.dullong.firedocmanager.lucene4;

import java.sql.Connection;
import java.sql.SQLException;
import java.util.List;

import org.apache.commons.dbutils.DbUtils;
import org.apache.commons.dbutils.QueryRunner;
import org.apache.commons.dbutils.handlers.BeanListHandler;
import org.apache.log4j.Logger;
import org.apache.lucene.search.Query;

import com.dullong.firedocmanager.bean.Document;
import com.dullong.firedocmanager.lucene4.domain.LDocument;
import com.dullong.firedocmanager.util.ConnectionUtil;

public class DocumentCreater {

	static Logger logger = Logger.getLogger(DocumentCreater.class);

	public static List<Document> creatDoc(Query query, Long... docid) {
		if (docid == null || docid.length == 0)
			return null;
		StringBuffer buffer = new StringBuffer();
		for (Long id : docid) {
			buffer.append(id).append(",");
		}
		logger.info("传递进来的docid个数为：" + docid.length + ",转换成的buffer为：" + buffer);
		String b = buffer.substring(0, buffer.length() - 1);
		logger.info("处理后的buffer为：" + b);
		Connection conn = ConnectionUtil.getConnection();
		QueryRunner runner = new QueryRunner();
		try {
			List<Document> list = runner.query(conn,
					"select * from document where id in (" + b + ") ",
					new BeanListHandler<Document>(Document.class));
			logger.info("查询出来的列表格式为：" + list.size());
			for (Document d : list) {
				String title = d.getTitle();
				String body = d.getBody();
				title = SearchHelper.highlight(query, title);
				body = SearchHelper.highlight(query, body);
				d.setBody(body);
				d.setTitle(title);
			}
			return list;
		} catch (SQLException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		} finally {
			DbUtils.closeQuietly(conn);
		}
		return null;

	}

	public static List<LDocument> creatDoc(Long... docid) {
		if (docid == null || docid.length == 0)
			return null;
		StringBuffer buffer = new StringBuffer();
		for (Long id : docid) {
			buffer.append(id).append(",");
		}
		logger.info("传递进来的docid个数为：" + docid.length + ",转换成的buffer为：" + buffer);
		String b = buffer.substring(0, buffer.length() - 1);
		logger.info("处理后的buffer为：" + b);
		Connection conn = ConnectionUtil.getConnection();
		QueryRunner runner = new QueryRunner();
		try {
			List<LDocument> list = runner
					.query(conn,
							"select id,title,page,type,uploadtime,cate,body,roleid from document where id in ("
									+ b + ") ", new BeanListHandler<LDocument>(
									LDocument.class));
			logger.info("查询出来的列表格式为：" + list.size());

			return list;
		} catch (SQLException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		} finally {
			DbUtils.closeQuietly(conn);
		}
		return null;

	}
}
